<template>

    <div class="p-2">
        <el-tabs v-model="activeTab" @tab-click="handleClick">
            <el-tab-pane label="样品管理" name="selectionSupermarket">
                <transition :enter-active-class="proxy?.animate.searchAnimate.enter"
                    :leave-active-class="proxy?.animate.searchAnimate.leave">
                    <div>
                        <searchrevealing>
                            <el-form :model="queryParams" ref="queryFormRef" :inline="true" label-width="88px">
                                <el-form-item label="商品名称" prop="styleName">
                                    <el-input v-model="queryParams.styleName" placeholder="请输入商品名称" clearable
                                        style="width: 220px" @keyup.enter="handleQuery" />
                                </el-form-item>
                                <el-form-item label="类目" prop="category">
                                    <el-cascader ref="categoryRef" v-model="queryParams.category" :props="categoryProps"
                                        style="width: 220px" @change="handleChange" placeholder="请选择类目" />
                                </el-form-item>
                                <el-form-item label="商品编码" prop="styleCode">
                                    <el-input v-model="queryParams.styleCode" placeholder="请输入商品编码" clearable
                                        style="width: 220px" @keyup.enter="handleQuery" />
                                </el-form-item>
                                <el-form-item label="供应商" prop="supplierName">
                                    <!-- <el-select v-model="queryParams.supplierName" placeholder="请选择供应商" clearable
                                        style="width: 220px">
                                        <el-option v-for="dict in hm_supplier_type" :key="dict.value"
                                            :label="dict.label" :value="dict.value" />
                                    </el-select> -->
                                    <el-select-v2 v-model="queryParams.supplierName" filterable clearable
                                        :options="supplierNameOptions" placeholder="请选择供应商" style="width: 220px" />
                                </el-form-item>
                                <el-form-item label="状态" prop="auditStatu">
                                    <el-select v-model="queryParams.auditStatu" placeholder="请选择状态" clearable
                                        style="width: 220px" @change="auditStatuChange">
                                        <el-option v-for="dict in auditStatusList" :key="dict.value" :label="dict.label"
                                            :value="dict.value" />
                                    </el-select>
                                </el-form-item>
                                <el-form-item label="招商部" prop="recruiterDept">
                                    <el-select style="width: 220px" v-model="queryParams.recruiterDept"
                                        placeholder="请选择招商部" clearable @change="deptChange">
                                        <el-option v-for="dict in deptList" :key="dict.deptId" :label="dict.deptName"
                                            :value="dict.deptId" />
                                    </el-select>
                                </el-form-item>
                                <el-form-item label="招商员" prop="recruiter">
                                    <el-select style="width: 220px" v-model="queryParams.recruiter" placeholder="请选择招商员"
                                        clearable>
                                        <el-option v-for="dict in recruiterList" :key="dict.userId"
                                            :label="dict.nickName" :value="dict.userId" />
                                    </el-select>
                                </el-form-item>
                                <el-form-item>
                                    <el-button type="primary" @click="handleQuery">查询</el-button>
                                    <el-button @click="resetQuery">重置</el-button>
                                </el-form-item>
                            </el-form>
                        </searchrevealing>
                        <el-card shadow="never">
                            <template #header>
                                <el-row :gutter="10" class="mb8">
                                    <el-col :span="1.5">
                                        <el-button type="primary" @click="handleProductSample()">商品到样</el-button>
                                    </el-col>
                                    <el-col :span="1.5">
                                        <el-button type="primary" :disabled="multiple"
                                            @click="invitation">样品邀约</el-button>
                                    </el-col>
                                    <el-col :span="1.5">
                                        <el-button type="primary" :disabled="multiple"
                                            @click="returnMerchants">退还商家</el-button>
                                    </el-col>
                                    <right-toolbar v-model:showSearch="showSearch"
                                        @queryTable="getList"></right-toolbar>
                                </el-row>
                            </template>
                            <el-table v-loading="loading" :data="supplierAddProductsList"
                                @selection-change="handleSelectionChange">
                                <el-table-column type="selection" width="55" align="center" />
                                <el-table-column label="供应商" align="center" prop="supplierName" />
                                <el-table-column label="商品名称" align="center" prop="styleName">
                                    <template #default="scope">
                                        <div class="color_theme">{{ scope.row.styleName }}</div>
                                    </template>
                                </el-table-column>
                                <el-table-column label="商品编码" align="center" prop="styleCode" />
                                <el-table-column label="商品主图" align="center" prop="productImage" width="100">
                                    <template #default="scope">
                                        <image-preview :src="scope.row.productImage" :width="50" :height="50" />
                                    </template>
                                </el-table-column>
                                <el-table-column label="类目" align="center" prop="categoryName">

                                </el-table-column>
                                <el-table-column label="招商员" align="center" prop="recruiter" />
                                <el-table-column label="品牌" align="center" prop="brand">
                                    <template #default="scope">
                                        {{ handleFilterBrand(scope.row.brand, brandList) }}
                                    </template>
                                </el-table-column>
                                <el-table-column label="店铺名称" align="center" prop="storeName" />
                                <el-table-column label="在售链接" align="center" prop="saleLink" show-overflow-tooltip>
                                    <template #default="scope">
                                        <el-link :href="scope.row.saleLink" type="primary" target="_blank">{{
                                            scope.row.saleLink
                                            }}</el-link>
                                    </template>
                                </el-table-column>
                                <el-table-column label="意向合作主播" align="center" prop="likePerson">
                                    <template #default="scope">
                                        <dict-tag :options="hm_anchor" :value="scope.row.likePerson" />
                                    </template>
                                </el-table-column>
                                <el-table-column label="直播机制" align="center" prop="liveStreamingMechanism" />
                                <el-table-column label="佣金" align="center" prop="commission" />
                                <el-table-column label="状态" align="center" prop="auditStatus">
                                    <template #default="scope">
                                        <div>{{ auditStatusNameById(scope.row.auditStatus) }}</div>
                                    </template>
                                </el-table-column>
                                <el-table-column label="快递物流单号" align="center" prop="trackingNumber" />
                                <el-table-column label="商品卖点" align="center" prop="sellingPoints" />
                                <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
                                    <template #default="scope">
                                        <el-button link type="primary" @click="handleInfo(scope.row)"
                                            class="color_theme">
                                            查看详情</el-button>
                                        <el-button link type="primary" @click="handleProductSample(scope.row)"
                                            class="color_theme" style="margin-left: 0px !important"
                                            :disabled="scope.row.auditStatus !== '6'">
                                            商品到样</el-button>
                                        <el-button link type="primary" @click="modify(scope.row)" class="color_theme"
                                            style="margin-left: 0px !important">
                                            修改</el-button>
                                        <el-button link type="primary" @click="hadleAgainInviteId(scope.row)"
                                            :disabled="scope.row.auditStatus !== '7'"
                                            style="margin-left: 0px !important">补样邀约</el-button>
                                    </template>
                                </el-table-column>
                            </el-table>
                            <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum"
                                v-model:limit="queryParams.pageSize" @pagination="getList" />
                        </el-card>
                    </div>
                </transition>
            </el-tab-pane>
            <el-tab-pane label="选品记录" name="selectionRecord">
                <selectionRecord v-if="activeTab == 'selectionRecord'" />
            </el-tab-pane>
            <el-tab-pane label="到样记录" name="sampleRecord">
                <sampleRecord v-if="activeTab == 'sampleRecord'" />
            </el-tab-pane>
            <el-tab-pane label="退还商家" name="returnMerchantList">
                <returnMerchantList v-if="activeTab == 'returnMerchantList'" />
            </el-tab-pane>
        </el-tabs>

        <!--商品详情抽屉 -->
        <commoditydetails @doClose="commoditydetailsClose" :commoditydetailsData="commoditydetailsData"
            :dialogInfoVisible="dialogInfoVisible"></commoditydetails>
        <!-- 商品到样 -->
        <productSample @doClose="cproductSampleClose" :productSampleData="productSampleData"
            :productSampleVisible="productSampleVisible"></productSample>
        <!-- 商品修改 -->
        <commoditymodify @doClose="commoditymodifyClose" :commoditymodifyData="commoditymodifyData"
            :commoditymodifyVisible="commoditymodifyVisible" :type="'commodity'"></commoditymodify>
        <!-- 退还商家 -->
        <returnMerchant @doClose="returnMerchantClose" :returnMerchantData="returnMerchantData"
            :returnMerchantVisible="returnMerchantVisible" />
    </div>
</template>
<script setup name="InvestmentPromotion" lang="ts">
import type { TabsPaneContext } from 'element-plus'
import { getDeptList, getUserById } from '@/api/group/qualityControl'
import sampleRecord from './components/sampleRecord.vue'
import returnMerchant from './components/returnMerchant.vue'
import returnMerchantList from './components/returnMerchantList.vue'
import selectionRecord from './components/selectionRecord.vue'
import { QualityControlForm, QualityControlQuery } from '@/api/group/qualityControl/types';
import { SupplierAddProductsVO } from '@/api/system/supplierAddProducts/types';
import { listSupplierAddProduct, getSupplierAddProducts, getproductscategorychildlistbypid } from '@/api/system/supplierAddProducts';
import { auditStatusNameById } from '@/utils/auditStatusFilter'
import { listBrand } from '@/api/system/brand';
import { BrandVO } from '@/api/system/brand/types';
import commoditydetails from '../components/commoditydetails.vue'
import productSample from './components/productSample.vue'
import commoditymodify from '../components/commoditymodify.vue'
import { hmSupplierList } from '@/api/group/supplier/index'
import { inviteId, againInviteId } from '@/api/group/investmentPromotion/index'
const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { hm_category } = toRefs<any>(proxy?.useDict('hm_category'));
const { hm_supplier_type } = toRefs<any>(proxy?.useDict('hm_supplier_type'));
const { hm_anchor } = toRefs<any>(proxy?.useDict('hm_anchor'));
const brandList = ref<BrandVO[]>([]);
const categoryRef = ref();


const deptList = ref<{ deptId: string; deptName: string; }[]>([])
const recruiterList = ref<{ userId: string; nickName: string; }[]>([])
const activeTab = ref('selectionSupermarket');
const showSearch = ref(true);
const loading = ref(true);
const supplierAddProductsList = ref<SupplierAddProductsVO[]>([]);
const total = ref(0);
const queryFormRef = ref<ElFormInstance>();
const ids = ref<Array<string | number>>([]);
const names = ref<Array<string>>([]);
const supplierNameOptions = ref<any[]>([])
const multiple = ref(true);
const selections = ref<SupplierAddProductsVO[]>()

const dialogInfoVisible = ref(false)
const commoditydetailsData = ref<QualityControlForm>({})

const productSampleVisible = ref(false)
const productSampleData = ref<SupplierAddProductsVO[]>()

const commoditymodifyVisible = ref(false)
const commoditymodifyData = ref<QualityControlForm>({})

const returnMerchantVisible = ref(false)
const returnMerchantData = ref<SupplierAddProductsVO[]>()


const data = reactive<PageData<QualityControlForm, QualityControlQuery>>({
    form: {},
    queryParams: {
        pageNum: 1,
        pageSize: 10,
        styleCode: undefined,
        category: undefined,
        supplierName: undefined,
        styleName: undefined,
        cooperationMode: undefined,
        recruiter: undefined,
        price: undefined,
        contractStatus: undefined,
        commission: undefined,
        auditStatus: undefined,
        auditStatu: undefined,
        kucun: undefined
    },
    rules: {}
});
const { queryParams, form, rules } = toRefs(data);

const auditStatusList = reactive([
    { label: '审核通过', value: '3' },
    { label: '待寄样', value: '4' },
    { label: '寄样中', value: '6' },
    { label: '已入库', value: '7' },
]);
/**
 * 获取供应商列表
 */
const getHmSupplierList = async() =>{
    const res = await hmSupplierList()
    supplierNameOptions.value = res.rows.map((item: any)=>(
        {
            label: item.supplierName,
            value: item.userId
        }
    ))
}
/**
 * tab点击事件
 * @param tab 
 */
const handleClick = (tab: TabsPaneContext) => {
    if (tab.paneName == 'selectionSupermarket') {
        getList()
    }
}
/** 补样邀约 */
const hadleAgainInviteId = async (row: SupplierAddProductsVO) => {
    await proxy?.$modal.confirm('是否确认补样邀约，商品名称为"' + row.styleName + '"的数据项？').finally(() => (loading.value = false));
    await againInviteId(row.id);
    proxy?.$modal.msgSuccess('样品邀约成功');
    await getList();
}
/** 
 * 样品邀约
 */
const invitation = async () => {
    const flag = selections.value?.every(item => item.auditStatus == '3')
    if (flag) {
        // 邀约
        await proxy?.$modal.confirm('是否确认邀约，商品名称为"' + names.value + '"的数据项？').finally(() => (loading.value = false));
        await inviteId(ids.value);
        proxy?.$modal.msgSuccess('样品邀约成功');
        await getList();
    } else {
        ElMessage.error('请选择状态为审核通过的商品');
    }
}
/**
 * 退还商家
 */
const returnMerchants = async () => {
    if (selections.value?.length) {
        const flag = selections.value.every(item => item.auditStatus == '7')
        const sign = selections.value[0].supplierName
        const supplierNameFlag = selections.value.every(item => item.supplierName == sign)
        if (supplierNameFlag) {

            if (flag) {
                returnMerchantVisible.value = true;
                returnMerchantData.value = selections.value
            } else {
                ElMessage.error('请选择状态为已入库的商品');
            }
        } else {
            ElMessage.error('您选择得样品属于不同供应商，无法一并退还，请按照供应商筛选样品进行批量退还');
        }
    }
}

/**
 * 退还商家关闭
 */
const returnMerchantClose = () => {
    returnMerchantVisible.value = false;
    getList();
}

// 类目请求方法封装
const ategoryQuest = (pid: string | number, level: any, resolve: (data: any) => void) => {
    getproductscategorychildlistbypid({ pid: pid }).then(res => {
        const datas = res.rows.map((value: { categoryId: string, categoryName: string }) => ({
            value: value.categoryId,
            label: value.categoryName,
            // leaf: level >= 3
        }));
        resolve(datas);
    })
}

// 筛选类目change事件
const handleChange = (val: [string, string, string, string]) => {
    if (val) {

        categoryRef.value.togglePopperVisible()
        queryParams.value.category = val[val.length - 1]
        queryParams.value.firstCategory = val[0]
        queryParams.value.secondCategory = val[1]
        queryParams.value.thirdCategory = val[2]
        queryParams.value.fourthCategory = val[3]
    }
}

// 类目props
const categoryProps = reactive({
    lazy: true,
    checkStrictly: true,
    lazyLoad(node: any, resolve: (data: any) => void) {
        const { level } = node
        const pid = !level ? 0 : node.value
        ategoryQuest(pid, level, resolve)
    }
})


/**
 * 获取招商部门信息
 */
const getDeptLists = async () => {
    const res = await getDeptList({ parentId: '1782395704411734018' })
    deptList.value = res.data
}

/**
 *  根据招商部获取招商员
 */
const deptChange = async (event: string) => {
    if (event) {
        const res = await getUserById(event)
        recruiterList.value = res.data
        queryParams.value.recruiter = undefined
    } else {
        recruiterList.value = []
        queryParams.value.recruiter = undefined
    }
}
/**
 * 获取品牌信息
 */
const getListBrand = async () => {
    const res = await listBrand()
    brandList.value = res.rows;
}
/**
 * 品牌检索value
 * @param para 
 * @param dict 
 */
const handleFilterBrand = (para: string | number | undefined, dict: Array<any>) => {
    let _label = '';
    dict.forEach((item: any) => {
        if (item.id == String(para)) {
            _label = item.brandName;
        }
    });
    return _label;
};

/** 查询供应商添加商品列表 */
const getList = async () => {
    try {
        loading.value = true;
        const res = await listSupplierAddProduct(queryParams.value);
        supplierAddProductsList.value = res.rows;
        total.value = res.total;
        loading.value = false;
    } catch (e) {
    } finally {
        loading.value = false;
    }
};
/** 搜索按钮操作 */
const handleQuery = () => {
    queryParams.value.pageNum = 1;
    getList();
};
/** 重置按钮操作 */
const resetQuery = () => {
    queryFormRef.value?.resetFields();
    queryParams.value.auditStatus = '3,4,6,7';
    handleQuery();
};
/**
 * 审核状态搜索
 */
const auditStatuChange = (value: string) => {
    queryParams.value.pageNum = 1;
    queryParams.value.auditStatus = value;
};
/** 多选框选中数据 */
const handleSelectionChange = (selection: SupplierAddProductsVO[]) => {
    console.log(selection)
    ids.value = selection.map((item) => item.id);
    names.value = selection.map((item) => item.styleName);
    selections.value = selection
    multiple.value = !selection.length;
};
/** 商品到样 */
const handleProductSample = (row?: SupplierAddProductsVO) => {
    // 单选
    if (row) {
        productSampleVisible.value = true;
        productSampleData.value = [row]
    } else {
        // 多选和空值
        // 多选
        if (selections.value?.length) {
            const flag = selections.value.every(item => item.auditStatus == '6')
            if (flag) {
                productSampleVisible.value = true;
                productSampleData.value = selections.value
            } else {
                ElMessage.error('请选择状态为寄样中的商品');
            }
        } else {
            productSampleVisible.value = true;
            productSampleData.value = selections.value
        }


    }
};
/** 修改 */
const modify = async (row?: SupplierAddProductsVO) => {
    const res: any = await getSupplierAddProducts((row as any).id);
    commoditymodifyData.value = res.data
    commoditymodifyVisible.value = true
};
/**
 * 修改关闭
 */
const commoditymodifyClose = () => {
    commoditymodifyVisible.value = false
    getList();
};

/** 商品到样关闭 */
const cproductSampleClose = () => {
    productSampleVisible.value = false;
    getList()
}
/** 查看商品详情 */
const handleInfo = (row?: SupplierAddProductsVO) => {
    nextTick(async () => {
        const _id = row?.id || ids.value[0];
        const res: any = await getSupplierAddProducts(_id);
        dialogInfoVisible.value = true;
        commoditydetailsData.value = res.data
    });
};
/** 商品详情关闭 */
const commoditydetailsClose = () => {
    dialogInfoVisible.value = false;
}
onMounted(() => {
    queryParams.value.auditStatus = '3,4,6,7';
    queryParams.value.pageNum = 1;
    getListBrand();
    getDeptLists();
    getHmSupplierList();
    getList();
});

</script>

<style lang="scss" scoped>
.mb96 {
    margin-bottom: 96px;
}

.color_theme {
    // color: rgba(1, 147, 255) !important;
}
</style>